//
//  HMStatusViewModel.swift
//  Weibo
//
//  Created by 米易雅克 on 16/4/18.
//  Copyright © 2016年 米易雅克. All rights reserved.
//

import UIKit
import SDWebImage

/// 处理HMStatusModel要处理的操作
class HMStatusViewModel: NSObject {

    //创建单例
    static let sharedInstance: HMStatusViewModel = HMStatusViewModel()
    
    //加载本地数据
    private func loadLocalStatuses() {
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")!
        let data = NSData(contentsOfFile: path)!
        
        //函数抛出异常在函数后面有throws，表示这段有可能会出现异常，如果我们处理这个异常，程序是不会挂掉的，如果不处理就会挂掉
        //try1:强制try ,有异常不处理，如果真的出现异常程序就挂掉了
        //do try catch； 处理异常，如果出现异常会走catch这个代码块，程序不会挂掉
        do {
        
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject]
            HMPrint("json:\(json)")
        } catch let error as NSError {
        HMPrint("json序列化异常:\(error)")
        }
    }
    
    //加载本地微博数据
    //since_id : 下拉刷新获取最新微博
    //max_id : 上拉加载以前的数据
    func loadStatus(since_id: Int64, max_id: Int64, loadstatusCallback: (statuses: [HMStatus]?, error: NSError?) -> ()) {
    
    //创建网络请求
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var parameters: [String: AnyObject] = ["access_token": HMUserAccountViewModel.sharedInstance.userAccount!.access_token!]
        
        //将since_id，max_id拼接到请求参数里
        if since_id > 0 {
            parameters["since_id"] = NSNumber(longLong: since_id)
        }else if max_id > 0 {
            parameters["max_id"] = NSNumber(longLong: max_id)
            
        }
        
        let debug = false
        if debug {
            //出错加载本地数据
            loadLocalStatuses()
            return
        }
        
        HMNetworkTool.sharedInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responseObject) in
          // HMPrint("获取微博数据成功\(responseObject)")
            
            if let dict = responseObject as? [String : AnyObject],let statusesDict = dict["statuses"] as? [[String: AnyObject]] {
            
            //二次转模型
                var statusModels: [HMStatus] = []
                
            //遍历字典
                for dict in statusesDict {
                
                    let status = HMStatus(dict: dict)
                    
                    statusModels.append(status)
                
                }
            //缓存图片
                self.cacheWebImage(statusModels, loadStatusCallback: loadstatusCallback)
            
            }
            
            }) { (task, error) in
//                HMPrint("微博数据加载失败\(error)")
                loadstatusCallback(statuses: nil, error: error)
        }
    
    }
//MARK: 图片缓存
    
    private func cacheWebImage(statuses: [HMStatus],loadStatusCallback: (statuses: [HMStatus]?, error: NSError?) -> ()) {
    //异步下载，回调控制器
        let group = dispatch_group_create()
        
        //判断每个模型是否要下载图片
        for status in statuses {
            //存放下载地址数组
            var downloadsURLs: [NSURL]?
            
            downloadsURLs = status.storePictureURLs
            //如果原创没有看被转发是否有要下载的
            if downloadsURLs == nil {
                downloadsURLs = status.retweeted_status?.storePictureURLs
            }
            
            //查看是否要下载图片
            if let urls = downloadsURLs {
                //如果只有一个，提前下载
            
                if urls.count == 1 {
                    //获取一张要下载的图片的地址
                    let  url = urls.first!
                    //异步下载图片
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadWithURL(url, options: [], progress: nil, completed: { (image, error, _, _) in
                        dispatch_group_leave(group)
                        
                        if error != nil {
                        HMPrint("图片下载失败:\(error)")
                            return
                        }
                        HMPrint("图片下载成功:\(url)")
                    })
                    
                }
            }
        }
    
        //监听所有微博图片下载完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { 
            HMPrint("异步下载完成")
            loadStatusCallback(statuses: statuses, error: nil)
        }
    }
}
